<?php
/**
 * 测评题目
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-17
 * Time: 下午2:37
 */
namespace app\modules\weixin\controllers;

use app\libs\Method;
use app\libs\Sms;
use app\libs\WeixinControl;
use app\modules\weixin\models\MemberOpenid;
use app\modules\weixin\models\Members;
use app\modules\weixin\models\User;
use app\modules\weixin\models\UserPhoneCode;
use app\modules\weixin\models\UserRandCode;
use app\modules\weixin\models\UserToken;
use yii;


class UserController extends WeixinControl
{

    public $enableCsrfValidation = false;

    /**
     * @Title  [列表]
     * @Author Don
     * @Date   2021-05-11
     * @return [type]
     */
    public function actionLogin()
    {
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
        $code = Yii::$app->request->get('code');
        $wxConfig = [
            'appid' => 'wxc5a6082e703c586d',
            'secret' => '6ee16eb5dcbf8c9399d351330b916f12'
        ];
        if($code){
            $arr = self::getOpenid($code,$wxConfig);
            $user = self::getNickname($arr);
            $image = base64_encode($user['headimgurl']);
        }
        $sql = "select * from db_thinku_ucenter.uc_member_openid where openId='{$arr['openid']}' AND type=1";
        $userInfo = Yii::$app->db->createCommand($sql)->queryOne();
        if($userInfo){
            $uid = $userInfo['uid'];
            $localUser = User::find()->where("uid=$uid")->one();
            if(!$localUser){
                list($uid,$username,$email,$phone,$nickname,$level) = uc_get_user($uid,1);
                $re = [
                    'code' => 1,
                    'info' => [
                        'uid' => $uid,
                        'username' => $username,
                        'email' => $email,
                        'phone' => $phone,
                        'nickname' => $nickname,
                        'level' => $level,
                    ],
                ];
                Method::confim_user($re['info']);
                User::updateAll(['image' => $user['headimgurl']],"uid=$uid");
            }
            $token = md5(time());
            UserToken::updateAll(['token' => $token,'createTime'=> time()],"uid=$uid");
            return $this->redirect("https://wx.thinkwithu.com/login?openId={$arr['openid']}&image=$image&nickname={$user['nickname']}&token=$token");
        }else{
            return $this->redirect("https://wx.thinkwithu.com/login?openId={$arr['openid']}&image=$image&nickname={$user['nickname']}&token=");
        }
    }

    /**
     * 短信md5随机数
     */
    public function actionPhoneRand(){
        $openId = Yii::$app->request->post('openId');
        $num = rand(10000,99999);
        $sign = UserRandCode::find()->where("openId='$openId'")->one();
        if($sign){
            $sign->code = $num;
            $sign->save();
        }else{
            $model = new UserRandCode();
            $model->openId = $openId;
            $model->code = $num;
            $model->save();
        }
        die(Method::jsonGenerate(1,['num' => $num]));
    }

    public function actionPhoneCode(){
        $str = Yii::$app->request->post('str');
        $openId = Yii::$app->request->post('openId');
        $sign = UserRandCode::find()->where("openId='$openId'")->one();
        if($sign){
            $md5 = md5(Yii::$app->params['mcode'].$sign->code);
            if($md5!=$str){
                die('error');
            }
        }else{
            die('error');
        }
        $sms = new Sms();

        $phoneNum = Yii::$app->request->post('phone');
        $message = '使用';
        $time = time()-180;
        $phoneLocalCode = UserPhoneCode::find()->where("phone='$phoneNum' AND createTime>=$time")->one();
        if($phoneLocalCode){
            die(Method::jsonGenerate(0,null,"3分钟内无法重新发送"));
        }
        if (!empty($phoneNum)) {
            $phoneCode = mt_rand(100000, 999999);
            $phoneSign = UserPhoneCode::find()->where("phone='$phoneNum'")->one();
            if($phoneSign){
                $phoneSign->code = $phoneCode;
                $phoneSign->createTime = time();
                $phoneSign->save();
            }else{
                $model = new UserPhoneCode();
                $model->phone = $phoneNum;
                $model->code = $phoneCode;
                $model->createTime = time();
                $model->save();
            }

            $content = '申友网验证码：' . $phoneCode . '（10分钟有效），您正在通过手机' . $message . '申友网免费会员！';
            $sms->send($phoneNum, $content, $ext = '', $stime = '', $rrid = '');

            $res['code'] = 1;
//            $res['phonecode'] = $phoneCode;

            $res['message'] = '短信发送成功！';

        } else {

            $res['code'] = 0;

            $res['message'] = '发送失败!手机号码为空！';

        }

        die(json_encode($res));
    }

    public function actionBindPhone(){
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
        $phone = Yii::$app->request->post('phone');
        $code = Yii::$app->request->post('code');
        $openId = Yii::$app->request->post('openId');
        $nickname = Yii::$app->request->post('nickname');
        $image = Yii::$app->request->post('image');
        $phoneLocalCode = UserPhoneCode::find()->where("phone='$phone'")->one();
        if($code != $phoneLocalCode->code){
            die(Method::jsonGenerate(0,null,"验证码错误"));
        }
        $userInfo = Members::find()->asArray()->where("phone='$phone'")->one();
        if($userInfo){
            $uid = $userInfo['uid'];
        }else{
            $username = 'sy'.time();
            $phonepass = '123456';
            $source = "雅思微信399";
            $ipInfo = Yii::$app->request->getUserIP();
            $data = Method::getIpInfo($ipInfo);
            // $country = $data[0];
            $city = $data;
            $uid = uc_user_register($username,$phonepass,'',$phone,$source,time(),'','',$ipInfo,$city,'');
            Members::updateAll(["nickname" => $nickname],"uid=$uid");
            $info = [
                'uid' => $uid,
                'username' => $username,
                'email' => '',
                'phone' => $phone,
                'nickname' => $nickname,
                'level' => '',
            ];
            Method::confim_user($info);
        }
        User::updateAll(['image' => base64_decode($image),'nickname' => $nickname],"uid=$uid");
        $model = new MemberOpenid();
        $model->openId=$openId;
        $model->uid=$uid;
        $model->type=1;
        $model->save();
        $token = md5(time());
        $model = new UserToken();
        $model->uid = $uid;
        $model->createTime = time();
        $model->token = $token;
        $model->save();
        UserPhoneCode::deleteAll("phone='$phone'");
        die(Method::jsonGenerate(1,['token' => $token]));
    }

    public static function getOpenid($code,$wxConfig)
    {
        $appid         = $wxConfig['appid'];
        $secret        = $wxConfig['secret'];
        $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $ch            = curl_init($get_token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data, true);
        return $data;
    }

    public static function getNickname($arr){
        $token = $arr['access_token'];
        $openid = $arr['openid'];
        //拿到token后就可以获取用户基本信息了
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid;
        $json = file_get_contents($url);//获取微信用户基本信息
        $arr = json_decode($json,true);
        return $arr;
    }

    public function actionGetUserInfo(){
        if(!$this->uid){
            die(Method::jsonGenerate(99));
        }
        $data = User::find()->asArray()->where("uid=$this->uid")->one();
        die(Method::jsonGenerate(1,['user' => $data]));
    }


}